package net.guerlab.smart.platform.user.service.service.impl;

import net.guerlab.commons.number.NumberHelper;
import net.guerlab.smart.platform.commons.exception.UserIdInvalidException;
import net.guerlab.smart.platform.server.service.BaseServiceImpl;
import net.guerlab.smart.platform.user.service.entity.OperationLog;
import net.guerlab.smart.platform.user.service.entity.User;
import net.guerlab.smart.platform.user.service.mapper.OperationLogMapper;
import net.guerlab.smart.platform.user.service.service.OperationLogService;
import net.guerlab.smart.platform.user.service.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 操作记录服务实现
 *
 * @author guer
 */
@Service
public class OperationLogServiceImpl extends BaseServiceImpl<OperationLog, Long, OperationLogMapper>
        implements OperationLogService {

    private static final String UNKNOWN = "unknown";

    private UserService userService;

    @Async
    @Override
    public void add(OperationLog entity) {
        String applicationName = StringUtils.trimToNull(entity.getApplicationName());
        if (applicationName == null) {
            applicationName = UNKNOWN;
        }
        String operationContent = StringUtils.trimToNull(entity.getOperationContent());
        if (operationContent == null) {
            operationContent = UNKNOWN;
        }

        User user = findUser(entity.getUserId());

        entity.setOperationLogId(sequence.nextId());
        entity.setApplicationName(applicationName);
        entity.setOperationTime(LocalDateTime.now());
        entity.setOperationContent(operationContent);
        entity.setOperationParams(StringUtils.trimToEmpty(entity.getOperationParams()));
        entity.setUsername(user.getUsername());
        entity.setName(user.getName());

        mapper.insertSelective(entity);
    }

    private User findUser(Long userId) {
        if (!NumberHelper.greaterZero(userId)) {
            throw new UserIdInvalidException();
        }

        User user = userService.selectById(userId);

        if (user == null) {
            user = new User();
            user.setUsername(UNKNOWN);
            user.setName(UNKNOWN);
        }

        return user;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
